import { Form, Select } from 'antd';
import React, { useEffect, useState } from 'react';

import { FormFieldBase } from '../../../typings/FormFieldBase';
import _ from 'lodash';

export type SearchSelectFormFieldProps = FormFieldBase & {};
export const SearchSelectFormField: React.FC<SearchSelectFormFieldProps> = (props) => {
  const { name, label, rules, dataSource, placeholder, config, light } = props;
  const [ data, setData ] = useState([]);
  const [ loading, setLoading ] = useState(false);
  const [ searchKey, setSearchKey ] = useState('');

  useEffect(() => {
    setLoading(true);
    (dataSource as any)(searchKey)
     ?.then((res: any) => {
       setLoading(false);
       setData(res);
     })
     .catch(() => {
       setLoading(false);
     })
  }, [searchKey]);

  const handleSearch = _.debounce((value) => {
    setSearchKey(value);
  }, 200);

  return (
    <Form.Item label={ light ? undefined : label} name={name} rules={rules}>
      <Select
        loading={loading}
        showSearch
        onSearch={handleSearch}
        filterOption={false}
         placeholder={placeholder}
         {...config}
      >
        {(data as any[])?.map((item: any, i: number) => (
          <Select.Option key={i} value={item.value}>
              {item.label}
          </Select.Option>
        ))}
      </Select>
    </Form.Item>
  )
}
